package demo1;

import java.util.Arrays;
import java.util.Comparator;

/**
 * @ClassDescription:
 * @JdkVersion: 1.8
 * @Author: 李白
 * @Created: 2024/5/17 16:50
 */
public class Test {
    public static void bubbleSort(Comparable[] comparables){
        for (int i = 0; i < comparables.length - 1; i++) {//三个数要跑两次是因为需要把两个较大的值放到后面
            for (int j = 0; j < comparables.length - 1; j++) {
                if (comparables[j].compareTo(comparables[j+1]) > 0){
                    Comparable tmp = comparables[j];
                    comparables[j] = comparables[j+1];
                    comparables[j+1] = tmp;
                }

            }
        }
    }
    public static void main(String[] args) {
        Student[] students = new Student[3];
        students[0] = new Student("zhangsan",12220);
        students[1] = new Student("lisi",2220);
        students[2] = new Student("wangwu",202);
        System.out.println("排序前："+Arrays.toString(students));
        bubbleSort(students);//因为student类实现了Comparable接口，所以可以直接使用students
        System.out.println("排序后："+Arrays.toString(students));
    }
    public static void main2(String[] args) {
        int[] array = {1,21,3,40};
        Arrays.sort(array);
        System.out.println(Arrays.toString(array));
    }
    public static void main1(String[] args) {
        Student student1 = new Student("zhangsan",19);
        Student student2 = new Student("lisi",10);
        System.out.println(student1.compareTo(student2));
        AgeComparator ageComparator = new AgeComparator();
        System.out.println(ageComparator.compare(student1, student2));
        NameComparator nameComparator = new NameComparator();
        System.out.println(nameComparator.compare(student1, student2));


    }
}
class AgeComparator implements Comparator<Student>{
    public int compare(Student o1,Student o2){//重写了compare方法
        return o1.age - o2.age;
    }
}
class NameComparator implements Comparator<Student>{
    public int compare(Student o1,Student o2){//重写了compare方法
        /**
         * 一个对象加一个"."，可以点出该对象的所属类所实现的方法
         */
        return o1.name.compareTo(o2.name);//name属于String类，所以compareTO也是String类里的方法
    }
}
class Student implements Comparable<Student>{
    public String name;
    public int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public int compareTo(Student o) {
        System.out.println("safdsfdsafdsfdsaf");
        return this.age - o.age;
       /* if (this.age > o.age){
            return 1;
        }else if (this.age == o.age){
            return 0;
        }else {
            return -1;
        }*/
    }
}
